package cc.wanforme.chipmunity.security.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import cc.wanforme.chipmunity.system.mapper.user.RoleAuthMapper;
import cc.wanforme.chipmunity.system.mapper.user.UserMapper;
import cc.wanforme.chipmunity.system.po.user.User;

/** 自定义的实现UserDetails
 * @author wanne
 * 2019年7月22日
 * 
 */
@Service
public class UserDetailsServiceImpl implements org.springframework.security.core.userdetails.UserDetailsService{

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private RoleAuthMapper roleAuthMapper;
	
	/** 获取用户信息*/
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = userMapper.selectUserByUsername(username);
		if(user==null) {
			throw new UsernameNotFoundException("用户不存在");
		}
/*		
		System.out.println(">>>>>>>>>>>>>>>");
		System.out.println("user: "+user);
		System.out.println(">>>>>>>>>>>>>>>");*/
		
		/*//设置用户具有的权限，这里简单起见就把数据库表示角色的字段当成了用户的权限
		List<SimpleGrantedAuthority> authorities = new ArrayList<>();
		authorities.add(new SimpleGrantedAuthority(user.getRole()));
		*/
		//获取并设置用户的权限
		List<SimpleGrantedAuthority> authorities = new ArrayList<>();
		List<String> userAuthorities = roleAuthMapper.selectAuthorities(user.getRole());
		for (String auth : userAuthorities) {
			authorities.add(new SimpleGrantedAuthority(auth));
		}
		 
		return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
	}

	
    public void validateUsernameAndPassword(String username, String password) throws AuthenticationException {
    	/* 这里是使用了自定义的User po实体，和User对应的Service，用于从数据库获取信息，并进行验证
        UserDO userDO = userService.getByUsername(username);
        if (userDO == null){
            throw new UsernameNotFoundException("user not exist");
        }
        if(!userDO.getPassword().equals(password)){
            throw new AuthenticationServiceException("error username or password");
        }
        */
    	/*这里的用了之前的写的UserDetailsService，里面从数据库获取信息，然后在这里验，也可以像上面那样自定义*/
    	
        UserDetails userDetails = this.loadUserByUsername(username);
        if(null == userDetails ) {
        	throw new UsernameNotFoundException("User not exist! ");
        }
        if(!userDetails.getPassword().equals(password)) {
        	throw new AuthenticationServiceException("error username or password! ");
        }
        
    }
	
}
